/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eit.ntc.lmsbackend.struts.action;

import com.eit.ntc.lmsbackend.struts.form.LMSForm;
import com.eit.ntc.lmsbackend.utils.RoleUtils;
import com.eit.ntc.spring.utils.CollectionUtils;
import com.eit.ntc.spring.utils.DateTimeUtils;
import com.eit.ntc.spring.utils.RequestUtils;
import com.eit.ntc.struts.action.AbstractWebFlowAction;
import com.eit.toschoolonline.lms.constant.LMSConstant;
import com.eit.toschoolonline.lms.jdo.CatalogM;
import com.eit.toschoolonline.lms.jdo.DownloadableItemM;
import com.eit.toschoolonline.lms.jdo.LearningItemM;
import com.eit.toschoolonline.lms.jdo.LessonM;
import com.eit.toschoolonline.lms.jdo.MetaDataLearningItemM;
import com.eit.toschoolonline.lms.jdo.SubjectM;
import com.eit.toschoolonline.lms.service.LearningItemService;
import com.eit.toschoolonline.lms.service.LessonService;
import com.eit.toschoolonline.lms.service.MetaDataMasterService;
import com.eit.toschoolonline.lms.service.SubjectService;
import com.eit.toschoolonline.lms.service.spring.CatalogServiceSpringBean;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.struts.upload.FormFile;
import org.springframework.validation.Errors;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

/**
 *
 * @author chanon
 */
public class ItemAction extends AbstractWebFlowAction {

    private LessonService lessonService;
    private SubjectService subjectService;
    private LearningItemService learningItemService;
    private MetaDataMasterService metaDataMasterService;
    private CatalogServiceSpringBean catalogServiceSpringBean;
//       private static String pathElab = "c:/content/Elab";
//       private static String pathEcouse = "c:/content/Ecouse";
//       private static String pathEtest = "c:/content/Etest";

    public Event MainItem(RequestContext context) throws Exception {

        LMSForm lForm = (LMSForm) getFormObject(context);
        lForm.setSubjectM(null);
        lForm.setLessonM(null);
        lForm.getLessonList().clear();
        lForm.getSubjectList().clear();
        lForm.setSelectSubject("");
        lForm.getItemList().clear();
        lForm.setActiveSelect("");
        lForm.setItemM(null);
        lForm.setActiveSelect("");
        SubjectService sservice = getSubjectService();
        lForm.setSubjectList(sservice.getSubjectAll());
        return new Event(this, "success");
    }

    public Event GetActiveItem(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        lForm.setActiveSelect("OPEN");
        SubjectService sservice = getSubjectService();

        lForm.getItemList().clear();
        lForm.setSelectType("");
        lForm.setSubjectM(sservice.getSubject(Integer.parseInt(lForm.getSelectSubject())));
        return new Event(this, "success");
    }

    public Event getAllCatalogLevel(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        LearningItemM item = lForm.getItemM();
        List catalogs = catalogServiceSpringBean.getLevelCatalogs();
        String username = getRemoteUser(context);
        item = learningItemService.getCatalogItemByCode(item.getItemCode());
        Set catalogSet = item.getCatalogs();
        String[] catalogCodes = CollectionUtils.set2Array(catalogSet, "catalogCode");
        lForm.setCatalogList(catalogs);
        lForm.setCatalogCodes(catalogCodes);
        lForm.setItemM(item);
        return success();

    }

    public Event updateCatalogLevel(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        LearningItemM item = lForm.getItemM();
        String[] catalogCodes = lForm.getCatalogCodes();

        List catalogList = catalogServiceSpringBean.getCatalogs(Arrays.asList(catalogCodes));
        Set catalogSet = new HashSet(catalogList);
        item.setCatalogs(catalogSet);
        item = learningItemService.updateLearningItem(item);
        lForm.setItemM(item);
        lForm.setSelectCatalogList(catalogList);
        return success();

    }

    public Event updateStatusItem(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        String status = lForm.getStatusItem();
        String comment = new String(lForm.getCommentItem());
        lForm.setCommentItem("");
        LearningItemM item = lForm.getItemM();
        item.setStatus(status);
        item.setComment(comment);
        learningItemService.updateLearningItem(item);
        return success();
    }

    public Event getAllItems(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        String username = getRemoteUser(context);
        lForm.getItemList().clear();
        String nameFilter = lForm.getItemNameFilter();
        String[] statusFilter = lForm.getStatusFilter();
        for (int i = 0; i < statusFilter.length; i++) {
            lForm.setSearchStatus(statusFilter[i]);
        }
        List statusList = Arrays.asList(statusFilter);
        List allItems = new ArrayList();
        if (RequestUtils.isAdminRole(context)) {
            if (nameFilter == null || nameFilter.trim().equals("")) {
                allItems = learningItemService.getAllItems(statusList);
            } else {
                allItems = learningItemService.getAllItemsByName(nameFilter, statusList);
            }
        } else {
            if (nameFilter == null || nameFilter.trim().equals("")) {
                allItems = learningItemService.getAllItems(username, statusList);
            } else {
                allItems = learningItemService.getAllItemsByName(nameFilter, username, statusList);
            }
        }
        ;
        lForm.setItemList(allItems);
        return success();
    }

    public Event GetItemByType(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        LearningItemService liservice = getLearningItemService();
        int id = Integer.parseInt(lForm.getSelectType());


        String code = lForm.getSelectSubject();

        lForm.setItemList(liservice.loadLearningItemBySubject(code, id));

        return new Event(this, "success");
    }

    public Event AddItem(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);

        lForm.setActiveSelect("");
        lForm.setItemName("");
        lForm.getLessonList().clear();
        //lForm.setSelectType("");
        lForm.setItemDescription("");
        lForm.setItemKeyword("");
        lForm.setSubjectM(null);
        lForm.setErrorMode("");

        return new Event(this, "success");
    }

    public Event addAllItem(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);

        LessonService lservice = getLessonService();
        SubjectService sservice = getSubjectService();

        List subjectList = sservice.getSubjectAll();
        lForm.setSubjectList(subjectList);


        String sCode = lForm.getSelectSubject();
        SubjectM sSubject = null;
        if (sCode!=null){
            sSubject = sservice.getSubjectByCode(sCode);
        };

        if (sSubject==null){
            if (subjectList.size()>0){
                sSubject = (SubjectM) subjectList.get(0);
            };
        };
        lForm.setSubjectM(sSubject);

        List lessonList = new ArrayList();
        if (sSubject!=null){
            lessonList = lservice.getLessonBySubject(sSubject.getSubjectCode());
        };
        lForm.setLessonList(lessonList);


        String lCode = lForm.getSelectLesson();
        lForm.setLessonCode("");
        if (lCode!=null){
            LessonM lesson = lservice.getLessonByCode(lCode);
            if (lesson!=null){
                lForm.setLessonCode(lesson.getLessonCode());
            };
        }


        lForm.setActiveSelect("");
        lForm.setItemName("");
        //lForm.getLessonList().clear();
        //lForm.setSelectType("");
        lForm.setItemDescription("");
        lForm.setItemKeyword("");
        lForm.setSubjectM(null);
        lForm.setErrorMode("");
       
        //lForm.setSelectSubject("S01");
        lForm.getMetaList().clear();
        lForm.setItemFileName("");
        lForm.setCatalogFlag(true);
        lForm.getSelectCatalogList().clear();

        return new Event(this, "success");
    }

    public Event SelectSubject(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        Errors errors = getFormErrors(context);
        System.out.println("user:" + getRemoteUser(context));
        System.out.println("role:" + RoleUtils.getRole(context));
        if (RoleUtils.getRole(context).equals(LearningItemM.NTC_ROLE)) {
            errors.reject("errors.item.notAuthorize");
            return new Event(this, "notAuthorize");
        }
        ;
        lForm.setActiveSelect("OPEN");
        lForm.setItemName("");
        lForm.getLessonList().clear();
        lForm.setItemDescription("");
        lForm.setItemKeyword("");
        LessonService lservice = getLessonService();
        SubjectService sservice = getSubjectService();
        SubjectM s = sservice.getSubjectByCode(lForm.getSelectSubject());
        lForm.setSubjectM(s);
        lForm.setLessonList(lservice.getLessonBySubject(s.getSubjectCode()));
        lForm.setSelectLesson("");
        return success();
    }

    public Event DelItem(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        String username = getRemoteUser(context);
        LearningItemService liservice = getLearningItemService();
        LearningItemM l = liservice.getCatalogItemByCode(Integer.parseInt(lForm.getInputID()), username);
        if (l != null) {
            l.setStatus(LearningItemM.DELETE_STATUS);
            l.getCatalogs().clear();
            liservice.updateLearningItem(l);
            // lForm.setSelectSubject(String.valueOf(lForm.getSubjectM().getSubjectId()));
            return success();
        }
        return error();
    }
//      public Event EditItem(RequestContext context) throws Exception {
//                LMSForm lForm = (LMSForm) getFormObject(context);
//                LearningItemService liservice = getLearningItemService();
//                 String itemID = getHttpServletRequestParameter(context,"id");
//                LearningItemM l = liservice.getLearningItem(Integer.parseInt(itemID));
//                lForm.setItemDescription(l.getItemDesc());
//                System.out.println("----------------------------"+l.getKeyword());
//                lForm.setItemKeyword(l.getKeyword());
//                lForm.setItemName(l.getItemName());
//                lForm.setItemFileName(l.getFilename());
//                lForm.setItemM(l);
//                lForm.setErrorMode("");
//             return new Event(this,"success");
//        }
//        ;
//        lForm.setActiveSelect("OPEN");
//        lForm.setItemName("");
//        lForm.getLessonList().clear();
//        lForm.setItemDescription("");
//        lForm.setItemKeyword("");
//        LessonService lservice = getLessonService();
//        SubjectService sservice = getSubjectService();
//        SubjectM s = sservice.getSubjectByCode(lForm.getSelectSubject());
//        lForm.setSubjectM(s);
//        lForm.setLessonList(lservice.getLessonBySubject(s.getSubjectCode()));
//        lForm.setSelectLesson("");
//        lForm.setSaved("");
//        return success();
//    }
//
//    public Event DelItem(RequestContext context) throws Exception {
//        LMSForm lForm = (LMSForm) getFormObject(context);
//        LearningItemService liservice = getLearningItemService();
//        LearningItemM l = liservice.getLearningItem(Integer.parseInt(lForm.getInputID()));
//        l.setStatus(LearningItemM.DELETE_STATUS);
//        liservice.updateLearningItem(l);
//        // lForm.setSelectSubject(String.valueOf(lForm.getSubjectM().getSubjectId()));
//        return new Event(this, "success");
//    }

    public Event EditItem(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        LearningItemService liservice = getLearningItemService();
        String itemID = getHttpServletRequestParameter(context, "id");
        LearningItemM l = liservice.getLearningItem(Integer.parseInt(itemID));
        lForm.setItemDescription(l.getItemDesc());
        System.out.println("----------------------------" + l.getKeyword());
        lForm.setItemKeyword(l.getKeyword());
        lForm.setItemName(l.getItemName());
        lForm.setItemFileName(l.getFilename());
        lForm.setItemM(l);
        lForm.setErrorMode("");
        return new Event(this, "success");
    }

    public Event editAllItem(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        LearningItemService liservice = getLearningItemService();
        String itemID = getHttpServletRequestParameter(context, "id");
        LearningItemM l = liservice.getCatalogItemByCode(Integer.parseInt(itemID));
        lForm.setItemDescription(l.getItemDesc());
        System.out.println("----------------------------" + l.getKeyword());
        lForm.setItemKeyword(l.getKeyword());
        lForm.setItemName(l.getItemName());
        lForm.setItemFileName(l.getFilename());
        lForm.setItemM(l);

        lForm.setSelectCatalogList(new ArrayList(l.getCatalogs()));
        
        lForm.setErrorMode("");
        return new Event(this, "success");
    }

    public Event SaveEditItem(RequestContext context) throws Exception {

        LMSForm lForm = (LMSForm) getFormObject(context);
        // LessonService lservice = getLessonService();
        LearningItemService liservice = getLearningItemService();
        // LessonM l = lservice.getLesson(Integer.parseInt(lForm.getSelectLesson()));
//        FormFile dFile = getFormFile(context,"itemFile");
//                lForm.getItemFile();
//        //Create Path
//        String path ="";
//        
//            path = "c:/learningitem/"+dFile.getFileName();
// 
//      //  Read & write File
//       
//        byte[] dFileData = dFile.getFileData();
//        
//        FileOutputStream fosDown = new FileOutputStream(path);
//                fosDown.write(dFileData);
//                fosDown.close();

        LearningItemM itemM = lForm.getItemM();
        itemM.setUpdateDate(DateTimeUtils.getEngNow());
        //itemM.setFilename(lForm.getItemName());
        itemM.setItemDesc(lForm.getItemDescription());

        itemM.setItemName(lForm.getItemName());

        itemM.setKeyword(lForm.getItemKeyword());

        itemM.setMetaDatas(lForm.getMetaList());


        liservice.updateLearningItem(itemM);
        return new Event(this, "success");
    }

    public Event cancelAddItem(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        System.out.println("cancel to add item");
        //lForm.setSelectSubject("");
        lForm.setSelectLesson("");
        return success();
    }

    public Event updateFileItem(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        LearningItemService service = getLearningItemService();
        String itemCode = getHttpServletRequestParameter(context, "itemCode");
        LearningItemM item = service.getLearningItemVersion(itemCode);
        lForm.setItemM(item);
        return success();

    }

    public Event saveUpdateFileItem(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        //FormFile dFile = getAjaxFormFileList(context,"docFile");
        //FileItem dFile = null;

        String dFileName = (String) getHttpServletSessionAttribute(context, "temp_filename");
        System.out.println("file name:" + dFileName);
        removeHttpServletSessionAttribute(context, "temp_filename");
        File dFile = new File(dFileName);
        long dFileSize = 0;
//            byte[] dFileData = null;
        String dFileType = "";
        // if (!fileList.isEmpty()){
        if (dFile != null) {
            //dFile = (FileItem) fileList.get(0);
            dFileName = dFile.getName();
            // dFileSize = dFile.get
            dFileSize = dFile.length();
//                FileInputStream fos = new FileInputStream(dFile);
//                fos.r
//                BufferedInputStream bis = new BufferedInputStream(fos);
//                bis.read(dFileData)
//                //dFileData = dFile.getFileData();
//                fos.r
            //dFileType = dFile.getContentType();
            }
        ;
        // FormFile dFile = getFormFile(context,"docFile");
        Errors errors = getFormErrors(context);
        String zipfileFlag = getHttpServletRequestParameter(context, "zipfile");
        boolean iszip = false;
        if (zipfileFlag != null && zipfileFlag.trim().equals("iszip")) {
            iszip = true;
        }
        ;
        System.out.println("+++++++++++++++++++++++++++++++++++" + dFileType);
        if (dFile != null && dFileName != null && !dFileName.equals("") && dFileSize > 0) {
            LearningItemM item = lForm.getItemM();
            // String filename = lForm.getDocFilename();
            String filename = getHttpServletRequestParameter(context, "docFilename");
            System.out.println("default file name:" + filename);
            if (filename == null || filename.trim().equals("")) {
                if (iszip) {
                    errors.reject("errors.UploadZipFileName");
                    return error();
                }
                System.out.println("upload filename:" + dFileName);
                filename = (String) getHttpServletSessionAttribute(context, "temp_name");
                removeHttpServletSessionAttribute(context, "temp_name");
            }
            ;
            item.setFilename(filename);

//                int nextItemCode = learningItemService.getMaxItemCode();
//                item.setItemCode(nextItemCode+1);
            item = learningItemService.updateLearningItem(item, dFile, iszip);
            lForm.setItemM(item);

            return success();
        } else {
            // Errors errors = getFormErrors(context);
            errors.rejectValue("docFile", "errors.FileNotFound", "File Not Found");
            return error();
        }
    }

    public Event cancelUpdateFileItem(RequestContext context) throws Exception {
        return success();
    }

//    public Event SaveItem(RequestContext context) throws Exception {
//       return success();
//    }
//       public Event cancelUpdateFileItem(RequestContext context) throws Exception {
//           return success();
//       }
    public Event saveAllItem(RequestContext context) throws Exception {

        LMSForm lForm = (LMSForm) getFormObject(context);
        LearningItemService service = getLearningItemService();
        Errors errors = getFormErrors(context);

        lForm.setErrorMode("");


        String zipfileFlag = getHttpServletRequestParameter(context, "zipfile");
        boolean iszip = false;
        if (zipfileFlag != null && zipfileFlag.trim().equals("iszip")) {
            iszip = true;
        }
        ;
        Event mappingEvent = null;
        MappingFileItemM mapFile = null;
        try {
            mapFile = mappingFileItem(context, iszip, mappingEvent);
        } catch (NotFoundFileException fileException) {
            fileException.printStackTrace();
            return new Event(this, "unFile");
        } catch (ZipFileException zipFileException) {
            zipFileException.printStackTrace();
            errors.reject("errors.UploadZipFileName");
            return error();
        }
        if (mapFile == null) {
            return error();
        }
        ;


        LessonService lService = getLessonService();
        LessonM l = lService.getDetailLessonByCode(lForm.getSelectLesson());
        if (l == null) {
            errors.rejectValue("selectLesson", "lessonError", "select correct Lesson");
            return error();
        }
        ;

        LearningItemM itemM = mappingItem(context);
        itemM.setFilename(mapFile.getFilename());
        itemM.setLessonId(l);
        itemM.setLessonName(l.getLessonName());
        itemM.setSubjectName(l.getSubject().getSubjectName());
        itemM.setMetaDatas(lForm.getMetaList());

        //Add Catalog List
//        List catCodeList = new ArrayList();
//        Iterator it = lForm.getCatalogList().iterator();
//        while (it.hasNext()) {
//            CatalogM cat = (CatalogM) it.next();
//            catCodeList.add(cat.getCatalogCode());
//        }
//        String[] chkCatalog = lForm.getChkCatalog();
//
        List catalogList = lForm.getSelectCatalogList();
//        if (chkCatalog!=null && chkCatalog.length>0){
//           catalogList = catalogServiceSpringBean.getCatalogs(chkCatalog);
//        }

        Set catalogSet = new HashSet(catalogList);
        itemM.setCatalogs(catalogSet);
        //Add Catalog List

        switch (itemM.getItemType()) {
            case LMSConstant.ItemTypeConstant.PDF_TYPE:
            case LMSConstant.ItemTypeConstant.MS_POWERPOINT_TYPE:

                DownloadableItemM dItemM = new DownloadableItemM(itemM);
                dItemM.setDocumentType(mapFile.getContentType());
                service.createDownloadableItemM(dItemM, mapFile.getUploadFile().getFileData(), iszip);
                break;
            default:
                service.createLearningItem(itemM, mapFile.getUploadFile().getFileData(), iszip);
                break;
        }

        // lForm.setSelectSubject(lForm.getSubjectM().getSubjectId()+"");

        return new Event(this, "success");


    }

    private LearningItemM mappingItem(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        LearningItemService liservice = getLearningItemService();
        int max = liservice.getMaxItemCode() + 1;

        LearningItemM itemM = new LearningItemM();
        itemM.setCreateDate(DateTimeUtils.getEngNow());
        //itemM.setFilename(lForm.getItemName());
        itemM.setItemDesc(lForm.getItemDescription());
        itemM.setOrderId(max);
        itemM.setItemCode(max);
        itemM.setItemName(lForm.getItemName());
        itemM.setOfflineCode(max);
        itemM.setItemType(Integer.parseInt(lForm.getSelectType()));
        itemM.setKeyword(lForm.getItemKeyword());

        itemM.setStatus(LearningItemM.ENABLE_STATUS);
        String role = RoleUtils.getRole(context);
        itemM.setUserRole(role);

        String owner = getRemoteUser(context);
        itemM.setOwnerUsername(owner);



        return itemM;
    }

    /**
     * @return the catalogServiceSpringBean
     */
    public CatalogServiceSpringBean getCatalogServiceSpringBean() {
        return catalogServiceSpringBean;
    }

    /**
     * @param catalogServiceSpringBean the catalogServiceSpringBean to set
     */
    public void setCatalogServiceSpringBean(CatalogServiceSpringBean catalogServiceSpringBean) {
        this.catalogServiceSpringBean = catalogServiceSpringBean;
    }

    private class MappingFileItemM {

        private String filename;
        private FormFile uploadFile;
        private String contentType;

        public MappingFileItemM(String filename, FormFile uploadFile, String cType) {
            this.filename = filename;
            this.uploadFile = uploadFile;
            this.contentType = cType;
        }

        /**
         * @return the filename
         */
        public String getFilename() {
            return filename;
        }

        /**
         * @param filename the filename to set
         */
        public void setFilename(String filename) {
            this.filename = filename;
        }

        /**
         * @return the uploadFile
         */
        public FormFile getUploadFile() {
            return uploadFile;
        }

        /**
         * @param uploadFile the uploadFile to set
         */
        public void setUploadFile(FormFile uploadFile) {
            this.uploadFile = uploadFile;
        }

        /**
         * @return the contentType
         */
        public String getContentType() {
            return contentType;
        }

        /**
         * @param contentType the contentType to set
         */
        public void setContentType(String contentType) {
            this.contentType = contentType;
        }
    }

    protected class NotFoundFileException extends Exception {
    }

    protected class ZipFileException extends Exception {
    }

    private MappingFileItemM mappingFileItem(RequestContext context, boolean iszip, Event nextEvent)
            throws NotFoundFileException, ZipFileException, Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        Errors errors = getFormErrors(context);



        FormFile dFile = getFormFile(context, "docFile");

        if (dFile == null || dFile.getFileName() == null || dFile.getFileName().trim().equals("")) {
            lForm.setErrorMode("กรุณาระบุไฟล์");
//                    nextEvent = new Event(this, "unFile");
//                    return null;
            throw new NotFoundFileException();
        }
        ;

        String filename = lForm.getItemFileName();
        if (filename == null || filename.trim().equals("")) {
            if (iszip) {
//                    errors.reject("errors.UploadZipFileName");
//                    nextEvent= error();
//                    return null;
                throw new ZipFileException();
            }
            filename = dFile.getFileName();
        }
        ;
        return new MappingFileItemM(filename, dFile, dFile.getContentType());


    }

    public Event SaveItem(RequestContext context) throws Exception {

        LMSForm lForm = (LMSForm) getFormObject(context);

        Errors errors = getFormErrors(context);
        LessonService lservice = getLessonService();
        lForm.setErrorMode("");
        LearningItemService liservice = getLearningItemService();
        LessonM l = lservice.getEnableLessonByCode(lForm.getSelectLesson());
        if (l == null) {
            errors.rejectValue("selectLesson", "lessonError", "select correct Lesson");
            return error();
        }
        ;

        String zipfileFlag = getHttpServletRequestParameter(context, "zipfile");
        boolean iszip = false;
        if (zipfileFlag != null && zipfileFlag.trim().equals("iszip")) {
            iszip = true;
        }
        ;
        Event mappingEvent = null;
        MappingFileItemM mapFile = mappingFileItem(context, iszip, mappingEvent);
        if (mapFile == null) {
            return mappingEvent;
        }
        ;


        LearningItemM itemM = mappingItem(context);
        itemM.setFilename(mapFile.getFilename());
        itemM.setLessonId(l);
        itemM.setLessonName(l.getLessonName());
        itemM.setSubjectName(lForm.getSubjectM().getSubjectName());
        itemM.setMetaDatas(lForm.getMetaList());
        liservice.createLearningItem(itemM, mapFile.getUploadFile().getFileData(), iszip);
        // lForm.setSelectSubject(lForm.getSubjectM().getSubjectId()+"");

        return new Event(this, "success");
    }

    public Event CancelItem(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);

        return new Event(this, "success");
    }

    public Event addKeywordAction(RequestContext context) throws Exception {

        LMSForm form = (LMSForm) getFormObject(context);
        form.setKeyword("");
        form.setValue("");
        form.setMetaMode("ADD");
        form.getMasterList().clear();
        form.setMasterList(getMetaDataMasterService().getMasterAll());
        if (form.getSaved() != null && form.getSaved().equals("")) {
            form.getMetaList().clear();
        }

        return success();
    }

    public Event addMetaDataAction(RequestContext context) throws Exception {

        LMSForm form = (LMSForm) getFormObject(context);
        MetaDataLearningItemM meta = new MetaDataLearningItemM();
        Errors error = getFormErrors(context);
        if (form.getValue() == null || form.getValue().equals("")) {
            error.reject("metadata.keywordEmpty");
            return error();
        }

        boolean flag = false;
        List list = form.getMetaList();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            MetaDataLearningItemM m = (MetaDataLearningItemM) it.next();
            if (m.getKeyword().equals(form.getKeyword())) {
                if (m.getValue().equals(form.getValue())) {
                    flag = true;
                }
            }
        }
        if (flag) {
            error.reject("metadata.keywordDuplicate");
            return error();
        }

        meta.setKeyword(form.getKeyword());
        meta.setValue(form.getValue());
        form.getMetaList().add(meta);

        return success();
    }

    public Event editMetaDataAction(RequestContext context) throws Exception {

        LMSForm form = (LMSForm) getFormObject(context);
        MetaDataLearningItemM meta = new MetaDataLearningItemM();
        meta = (MetaDataLearningItemM) form.getMetaList().get(Integer.parseInt(form.getIndexMeta()));
        form.setKeyword(meta.getKeyword());
        form.setValue(meta.getValue());

        return success();
    }

    public Event saveEditMetaDataAction(RequestContext context) throws Exception {

        LMSForm form = (LMSForm) getFormObject(context);
        MetaDataLearningItemM meta = new MetaDataLearningItemM();
        Errors error = getFormErrors(context);
        if (form.getValue() == null || form.getValue().equals("")) {
            error.reject("metadata.keywordEmpty");
            return error();
        }
        meta.setKeyword(form.getKeyword());
        meta.setValue(form.getValue());
        form.getMetaList().remove(Integer.parseInt(form.getIndexMeta()));
        form.getMetaList().add(meta);

        return success();
    }

    public Event deleteMetaDataAction(RequestContext context) throws Exception {

        LMSForm form = (LMSForm) getFormObject(context);
        form.getMetaList().remove(Integer.parseInt(form.getIndexMeta()));

        return success();
    }

    public Event editKeywordAction(RequestContext context) throws Exception {

        LMSForm form = (LMSForm) getFormObject(context);
        form.setKeyword("");
        form.setValue("");
        form.setMetaMode("EDIT");
        form.getMasterList().clear();
        form.setMasterList(getMetaDataMasterService().getMasterAll());
        LearningItemM l = getLearningItemService().getLearningItemDetach(form.getItemM().getItemId());

//        List metaList = new ArrayList();
//        Iterator it = l.getMetaDatas().iterator();
//        while (it.hasNext()) {
//            MetaDataLearningItemM meta = new MetaDataLearningItemM();
//            meta =  (MetaDataLearningItemM) it.next();
//            metaList.add(meta);
//        }
//        form.setMetaList(metaList);
        form.setMetaList(l.getMetaDatas());

        return success();
    }

    public Event saveMetaDataAction(RequestContext context) throws Exception {

        LMSForm form = (LMSForm) getFormObject(context);
        LearningItemM l = form.getItemM();
        l.setMetaDatas(form.getMetaList());

        getLearningItemService().updateLearningItem(l);

        return success();
    }

    public Event itemListCatalogAction(RequestContext context) throws Exception {

        LMSForm form = (LMSForm) getFormObject(context);
        form.setCatalogList(catalogServiceSpringBean.getLevelCatalogs());
        if (form.isCatalogFlag()) {
            form.setChkCatalog(null);
        }

        return success();
    }

    public Event itemAddCatalogAction(RequestContext context) throws Exception {

        LMSForm form = (LMSForm) getFormObject(context);
        String[] arr = form.getChkCatalog();
        List catalogList = new ArrayList();
        for (int i = 0; i < arr.length; i++) {
            CatalogM cat = (CatalogM) form.getCatalogList().get(Integer.parseInt(arr[i]));
            catalogList.add(cat);
        }
        form.getCatalogList().clear();
        form.setSelectCatalogList(catalogList);
        form.setCatalogFlag(false);

        return success();
    }

    public LessonService getLessonService() {
        return lessonService;
    }

    public void setLessonService(LessonService lessonService) {
        this.lessonService = lessonService;
    }

    public SubjectService getSubjectService() {
        return subjectService;
    }

    public void setSubjectService(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    public LearningItemService getLearningItemService() {
        return learningItemService;
    }

    public void setLearningItemService(LearningItemService learningItemService) {
        this.learningItemService = learningItemService;
    }

    public MetaDataMasterService getMetaDataMasterService() {
        return metaDataMasterService;
    }

    public void setMetaDataMasterService(MetaDataMasterService metaDataMasterService) {
        this.metaDataMasterService = metaDataMasterService;
    }
}
